package edu.xhu.video.interceptor;

import edu.xhu.model.biliuser.pojos.BiliUser;
import edu.xhu.utils.common.AppJwtUtil;
import edu.xhu.utils.thread.BiliUserThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class VideoTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        if (token == null) {
            return true;
        }
        // 解析token
        Claims claims = AppJwtUtil.getClaimsBody(token);
        if (claims == null) {
            return false;
        }
        // 获取用户id
        Long userId = (Long) claims.get("id");
        if (userId == null) {
            return false;
        }
        BiliUser biliUser = new BiliUser();
        biliUser.setUserId(userId);
        BiliUserThreadLocalUtil.setUser(biliUser);
        BiliUser currentUser = BiliUserThreadLocalUtil.getUser();
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BiliUserThreadLocalUtil.clear();
    }

}
